from bs4 import BeautifulSoup
from loguru import logger

from com.arcfox.manager.redis_task_manager import RedisTaskManager
from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.muilty_coroutine_util import concurrency
import com.arcfox.school.util.yzy_decrypt_util as yzy_util


class YZYUniversityEnrollProcessor(BaseProcessor):

    async def parse_info_url_list(self, result_arr, university_name):
        # https://www.youzy.cn/colleges/admissions-guide/detail?id=6254cb5ea878024933ee782b&collegeCode=10003
        parse_result = []
        for item in result_arr:
            url = f'https://www.youzy.cn/colleges/admissions-guide/detail?id={item["id"]}&collegeCode={item["collegeCode"]}'
            # 第一次爬取可以不用校验
            # exist = await self.__exist_university_enroll_info(item['id'])
            # if exist:
            #     # 如果存在则可以直接停止，说明已经是最新的，
            #     break
            university_uid = self.generate_school_uid(university_name)
            parse_result.append({
                "url": url,
                "enroll_info_id": item['id'],
                "university_uid": university_uid,
                "university_name": university_name,
                "title": item['title'],
                "source": item["editor"],
                "publish_time": item["updatedAt"],
                "data_source": "yzy"
            })
        return parse_result

        # await self.__insert_province_score(tasks=parse_result)

    async def parse_content_and_save(self, item, response_item):
        item["content"] = response_item["result"]["content"]
        await self.__insert_university_enroll_info(item)

    async def __insert_university_enroll_info(self, item):
        mapping = db.MysqlMapping("tb_university_enroll_info")
        exist = await mapping.query(
            {
                "enroll_info_id": item["enroll_info_id"]
            }, ["id"])
        if exist:
            logger.info("已经存在{}", item["enroll_info_id"])
            return
        await mapping.insert(item)

    async def __exist_university_enroll_info(self, enroll_info_id):
        mapping = db.MysqlMapping("tb_university_enroll_info")
        exist = await mapping.query(
            {
                "enroll_info_id": enroll_info_id
            }, ["id"])
        if exist:
            logger.info("已经存在{}", exist)
            return True
        return False
